<?php

namespace Beerus\Modules\Brand\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\model\brand\Brand;
use Biz\model\brand\BrandOrder;
use Biz\model\brand\BrandPackage;
use Biz\pockets\excel\DownExcel;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

/**
 * 品牌订单管理
 *
 * @category   Module name
 * @package    PSR
 * @subpackage Documentation\API
 * @author     zhouyang  <zhouyang@haohaozhu.com>
 * @license    GPL http://www.haohaozhu.com
 * @link       http://www.haohaozhu.com
 */
class BrandOrderController extends Controller
{
    const PAGE_SIZE = 20;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    public function index(Request $request, Content $content)
    {
        $request_data = $request->all();

        $page_size = $request->input("per_page", self::PAGE_SIZE);
        $page = $request->input("page", 1);

        $condition = [
            'order_status' => BrandOrder::ORDER_STATUS_FINISHED,
        ];
        if (!empty($request_data['brand_id'])) {
            $condition['brand_id'] = $request_data['brand_id'];
        }

        if (!empty($request_data['brand_name'])) {
            $condition['brand_name[~]'] = $request_data['brand_name'];
        }

        if (!empty($request_data['pay_platform'])) {
            $condition['pay_platform'] = $request_data['pay_platform'];
        }

        if (!empty($request_data['package_id'])) {
            $condition['package_id'] = $request_data['package_id'];
        }

        if (!empty($request_data['pay_time']['start'])) {
            $condition['pay_time[>=]'] = strtotime($request_data['pay_time']['start']);
        }

        if (!empty($request_data['pay_time']['end'])) {
            $condition['pay_time[<=]'] = strtotime($request_data['pay_time']['end']);
        }

        $condition['ORDER'] = ['id' => 'DESC'];
        $condition['LIMIT'] = [
            ($page - 1) * $page_size,
            $page_size
        ];

        $lists = BrandOrder::select('*', $condition);

        $total = 0;
        if (!empty($lists)) {
            unset($condition['ORDER']);
            unset($condition['LIMIT']);
            $total = BrandOrder::count($condition);
        }

        $gridModel = new pGridDataModel($lists, $total, [
            'perPage' => $page_size
        ]);

        $all_package = BrandPackage::getAll();
        foreach ($all_package as $item) {
            $packages[$item['id']] = $item['package_name'];
        }

        $search_params = http_build_query($condition);
        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel, $search_params, $packages) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();
                // 添加导出按钮
                $grid->tools(function (Grid\Tools $tool) use ($grid, $search_params) {
                    $url = url('/admin/brand/export_order?' . $search_params);
                    $button = '<div class="btn-group download" style="margin-right: 10px">
                        <a class="btn btn-sm btn-primary" target="_blank" href="' . $url . '">
                        <i class="fa fa-download"></i>
                        <span class="hidden-xs">导出订单表</span></a>
                    </div>';
                    $tool->append($button);
                });

                $grid->filter(function (Grid\Filter $filter) use ($packages) {
                    $filter->disableIdFilter();
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('brand_id', '品牌ID')->placeholder('请输入品牌id');
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('brand_name', '品牌名称')->placeholder('请输入品牌名称');
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('pay_platform', '支付方式')->radio(BrandOrder::PAY_PLATFORM);
                    });
                    $filter->column(1 / 2, function ($filter) use ($packages) {
                        $filter->equal('package_id', '服务套餐')->select($packages);
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->between('pay_time', '支付时间')->datetime();
                    });
                    $filter->expand();
                });

                $grid->column('dsn', '品牌订单号');
                $grid->column('brand_name', '品牌名称');
                $grid->column('brand_id', '品牌id');
                $grid->column('package_name', '服务套餐');
                $grid->column('identify', '标识');
                $grid->column('pay_time', '支付时间')->display(function () {
                    if (empty($this->pay_time)) {
                        return '';
                    }
                    return date('Y-m-d H:i:s', $this->pay_time);
                });
                $grid->column('pay_platform', '支付方式')->display(function () {
                    if (empty($this->pay_platform)) {
                        return '';
                    }
                    return BrandOrder::PAY_PLATFORM[$this->pay_platform];
                });
                $grid->column('other_sn', '第三方交易流水号');
                $grid->column('product_price', '套餐金额');
                $grid->column('in_start_time', '入驻时间')->display(function () {
                    return $this->in_start_time . '至' . $this->in_end_time;
                });
                $grid->column('service_status', '服务状态')->display(function () {
                    return BrandOrder::SERVICE_STATUS_MAP[$this->service_status];
                });
                $grid->column('amount', '实付金额');
                $grid->column('admin_id', '操作人')->display(function () {
                    if (!$this->admin_id) {
                        return '-';
                    } else {
                        return Admin::user()->find($this->admin_id)->name;
                    }
                })->width(60);
                $grid->column('remark', '描述');

                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableDelete();
                    $actions->disableEdit();
                });
            }
        );

        $tab = new Tab();
        $tab->add('品牌订单列表', $gridList->render());
        $content->row($tab);
        return $content
            ->header('品牌订单列表')
            ->description(' ')
            ->breadcrumb(['text' => '品牌订单列表']);
    }

    public function exportOrder(Request $request)
    {
        $request_data = $request->all();

        $condition = [
            'order_status' => BrandOrder::ORDER_STATUS_FINISHED,
        ];

        if (!empty($request_data['brand_id'])) {
            $condition['brand_id'] = $request_data['brand_id'];
        }

        if (!empty($request_data['brand_name'])) {
            $condition['brand_name[~]'] = $request_data['brand_name']['~'];
        }

        if (!empty($request_data['pay_platform'])) {
            $condition['pay_platform'] = $request_data['pay_platform'];
        }

        if (!empty($request_data['package_id'])) {
            $condition['package_id'] = $request_data['package_id'];
        }

        if (!empty($request_data['pay_time']['>='])) {
            $condition['pay_time[>=]'] = $request_data['pay_time']['>='];
        }

        if (!empty($request_data['pay_time']['<='])) {
            $condition['pay_time[<=]'] = $request_data['pay_time']['<='];
        }

        $testBandIds = Brand::select('id', ['is_test' => 1]);
        if (!empty($testBandIds)) {
            $condition['brand_id[!]'] = $testBandIds;
        }

        $lists = BrandOrder::select('*', $condition);

        if (empty($lists)) {
            $success = new MessageBag([
                'title' => '暂无查询数据导出'
            ]);

            return back()->with(compact('success'));
        } else {
            $data = [];
            foreach ($lists as $item) {
                $data[] = [
                    'dsn' => $item['dsn'],
                    'brand_name' => $item['brand_name'],
                    'brand_id' => $item['brand_id'],
                    'package_name' => $item['package_name'],
                    'identify' => $item['identify'],
                    'pay_time' => date('Y-m-d H:i:s', $item['pay_time']),
                    'pay_platform' => BrandOrder::PAY_PLATFORM[$item['pay_platform']],
                    'other_sn' => $item['other_sn'],
                    'product_price' => $item['product_price'],
                    'amount' => $item['amount'],
                    'in_start_time' => $item['in_start_time'],
                    'in_end_time' => $item['in_end_time'],
                    'service_status' => BrandOrder::SERVICE_STATUS_MAP[$item['service_status']],
                ];
            }

            // 设置列宽
            $header = [
                '品牌订单号', '品牌名称', '品牌id', '服务套餐', '标识', '支付时间', '支付方式',
                '第三方交易流水号', '套餐金额', '实付金额', '入驻开始时间', '入驻结束时间', '服务状态'
            ];
            $letter = range('A', 'M');
            $excel_obj = new DownExcel();
            $excel_obj->setFileName('品牌订单表 - ' . date('YmdHis'));
            $excel_obj->setSheetTitle('品牌订单表');

            $widths = [
                'A' => 20,
                'B' => 22,
                'C' => 12,
                'D' => 25,
                'E' => 25,
                'F' => 23,
                'G' => 13,
                'H' => 35,
                'I' => 20,
                'J' => 20,
                'K' => 20,
                'L' => 20,
                'M' => 20,
            ];

            $excel_obj->setWidth($widths);
            $excel_obj->setDefaultStyleAlignment();

            foreach ($header as $key => $value) {
                // 设置字体
                $excel_obj->setFrontName($letter[$key]);
                // 设置加粗
                //$excel_obj->setFrontBold("$letter[0]1");
                // 设置大小
                $excel_obj->setFrontSize($letter[$key]);
            }

            $excel_obj->create($data, $header);
        }
    }
}
